//
//  TravelViewController.m
//  demo
//
//  Created by dllo on 15/7/11.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "TravelViewController.h"
#import "AFNetworkHandler.h"
#import "Travel.h"
#import "TravelTableViewCell.h"
#import "AreaCollectionViewCell.h"
#import "SegmentedControl.h"
#import "SearchViewController.h"
#import "TravelPushViewController.h"
#import "UIViewController+Example.h"
#import "MJRefresh.h"
#import "SearchResultViewController.h"
#import "NoteResultViewController.h"
#import "SearchResultViewController.h"

static int page = 1;
@interface TravelViewController () <UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UIScrollViewDelegate, UISearchBarDelegate>
@property (nonatomic, retain) NSMutableArray *arr;
@property (nonatomic, retain) NSMutableArray *areaArrM;
@property (nonatomic, retain) NSMutableArray *areaArrW;
@property (nonatomic, retain) NSMutableArray *areaArrN;
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) UICollectionView *collectionView;
@property (nonatomic, retain) UISegmentedControl *seg;
@property (nonatomic, retain) UISearchBar *searchBar;
@property (nonatomic, retain) SearchResultViewController *searchRvc;
@end

@implementation TravelViewController
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self scrollViewDidScroll:nil];
}
/**
 *  视图将要出现
 *
 *  @param animated
 */
- (void)viewWillAppear:(BOOL)animated
{
    self.searchBar.hidden = YES;
    self.navigationItem.title = @"游记";
    self.tabBarController.tabBar.hidden = NO;
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"title.jpg"] forBarMetrics:UIBarMetricsDefault];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(search)];
    self.arr = [NSMutableArray array];
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(10, 15, self.view.bounds.size.width - 65, 10)];
    self.searchBar.delegate = self;
    self.searchBar.showsCancelButton = NO;
    self.searchBar.barStyle = UIBarStyleDefault;
    self.searchBar.placeholder = @"搜索游记,旅行地";
    self.searchBar.keyboardType = UIKeyboardTypeNamePhonePad;
    self.searchBar.hidden = YES;
    [self.navigationController.navigationBar addSubview:self.searchBar];
    [_searchBar release];
    [self setSearchResultVc];
    [self createTableView];
    [self getData:page where:nil];
    [self exampleUpPush];
    [self exampleDownPush];
    // Do any additional setup after loading the view.
}
/**
 *  上拉刷新
 */
- (void)exampleDownPush
{
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadMoreData方法）
    self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
}
/**
 *  下拉刷新
 */
- (void)exampleUpPush
{
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadNewData];
    }];
    // 马上进入刷新状态
    [self.tableView.header beginRefreshing];
}
/**
 *  loadNewData
 *
 */
- (void)loadNewData
{
    NSString *where = @"downPush";
    static int a = 1;
    [self getData:a where:where];
    page = 1;
}
/**
 *  loadMoreData
 */
- (void)loadMoreData
{
    // 1.向上拖动时page自加
    NSString *where = @"upPush";
    page++;
    [self getData:page where:where];
}
/**
 *  取消方法
 */
- (void)cancle
{
    //动画效果 // 从下往上
    CATransition *animation = [CATransition animation];
    animation.duration = .3f;
    animation.timingFunction = UIViewAnimationCurveEaseInOut;
    animation.fillMode = kCAFillModeRemoved;
    animation.type = kCATransitionReveal;
    animation.subtype = kCATransitionFromTop;
    [self.collectionView.layer addAnimation:animation forKey:@"animation"];
    self.collectionView.hidden = YES;
    self.searchBar.hidden = YES;
    [self.searchBar resignFirstResponder];
    self.navigationItem.title = @"游记";
    self.seg.selectedSegmentIndex = 0;
    self.searchRvc.view.hidden = YES;
    self.tableView.hidden = NO;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(search)];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    self.collectionView.hidden = YES;
    self.searchRvc.view.hidden = NO;
    self.tableView.hidden = YES;
    [self.searchBar resignFirstResponder];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"passStr" object:searchBar.text userInfo:@{@"name":@"NotificationCenter", @"type":@"type"}];
}
#pragma mark - segmentedControl 点击事件
- (void)segAction:(UISegmentedControl *)seg
{
    if (seg.selectedSegmentIndex == 0) {
        [self.collectionView reloadData];
    } else {
        [self.collectionView reloadData];
    }
}
- (void)search
{
    [self createCollectionView];
    self.navigationItem.title = nil;
    self.searchBar.hidden = NO;
    [self.searchBar becomeFirstResponder];
    NSString * str = @"http://chanyouji.com/api/destinations.json";
    [AFNetworkHandler GetWithAFNByURL:str completion:^(id result) {
        NSArray *tempArr = result;
        NSMutableArray *tempArrN = [NSMutableArray array];
        NSMutableArray *tempArrW = [NSMutableArray array];
        for (NSInteger i = 0; i < 3; i++) {
            [tempArrW addObject:result[i]];
        }
        for (NSInteger i = 3; i < tempArr.count; i++) {
            [tempArrN addObject:tempArr[i]];
        }
        self.areaArrW = [NSMutableArray array];
        self.areaArrN = [NSMutableArray array];
        for (NSDictionary *dic in tempArrW) {
            NSArray *arr = [dic objectForKey:@"destinations"];
            NSArray *arrr = [Area arrayWithModelByArray:arr];
            for (Area *a in arrr) {
                [self.areaArrW addObject:a];
            }
        }
        for (NSDictionary *dic in tempArrN) {
            NSArray *arr = [dic objectForKey:@"destinations"];
            NSArray *arrr = [Area arrayWithModelByArray:arr];
            for (Area *a in arrr) {
                [self.areaArrN addObject:a];
            }
        }
        self.seg.selectedSegmentIndex = 0;
        [self.collectionView reloadData];
    }];
}
- (void)createCollectionView
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    //设置头部区域
    layout.headerReferenceSize = CGSizeMake(self.view.bounds.size.width, 30);
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    
    //动画效果 // 从上往下
    CATransition *animation = [CATransition animation];
    //animation.delegate = self;
    animation.duration = .3f;
    animation.timingFunction = UIViewAnimationCurveEaseInOut;
    animation.fillMode = kCAFillModeForwards;
    animation.type = kCATransitionMoveIn;
    animation.subtype = kCATransitionFromBottom;
    [self.collectionView.layer addAnimation:animation forKey:@"animation"];
    
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    [self.collectionView registerClass:[AreaCollectionViewCell class] forCellWithReuseIdentifier:@"cCell"];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.collectionView];
    self.collectionView.contentInset = UIEdgeInsetsMake(10, 0, 0, 0);
    [_collectionView release];
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    SearchViewController *searchPvc = [[SearchViewController alloc] init];
    if (self.seg.selectedSegmentIndex == 0) {
        searchPvc.name = [self.areaArrW[indexPath.item] name_zh_cn];
        searchPvc.passId = [self.areaArrW[indexPath.item] areaId].stringValue;
    } else {
        searchPvc.name = [self.areaArrN[indexPath.item] name_zh_cn];
        searchPvc.passId = [self.areaArrN[indexPath.item] areaId].stringValue;
    }
    self.collectionView.hidden = YES;
    self.searchBar.hidden = YES;
    [self.searchBar resignFirstResponder];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(search)];
    [self.navigationController pushViewController:searchPvc animated:YES];
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    AreaCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cCell" forIndexPath:indexPath];
    if (self.seg.selectedSegmentIndex == 0) {
        cell.area = self.areaArrW[indexPath.item];
    } else {
        cell.area = self.areaArrN[indexPath.item];
    }
    return cell;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.seg.selectedSegmentIndex == 0) {
        return self.areaArrW.count;
    } else {
        return self.areaArrN.count;
    }
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind == UICollectionElementKindSectionHeader) {
        UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
        header.backgroundColor = [UIColor whiteColor];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancle)];
        self.seg = [SegmentedControl shareInstance];
        self.seg.frame = CGRectMake(header.frame.origin.x + 30, header.frame.origin.y, header.frame.size.width - 60, 30);
        self.seg.tintColor = [UIColor colorWithRed:56 / 255.0 green:152 / 255.0 blue:135 / 255.0 alpha:1];
        [self.seg addTarget:self action:@selector(segAction:) forControlEvents:UIControlEventValueChanged];
        [header addSubview:self.seg];
        return header;
    } else {
        return nil;
    }
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(110, 30);
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(collectionView.frame.size.width, 30);
}
- (void)getData:(int)page where:(NSString *)where;
{
    NSString * str = [NSString stringWithFormat:@"http://chanyouji.com/api/trips/featured.json?page=%d", page];
    [AFNetworkHandler GetWithAFNByURL:str completion:^(id result) {
        NSArray *tempArr = result;
        NSMutableArray *temp = [NSMutableArray array];
        temp = [Travel arrayWithModelByArray:tempArr];
        
        if ([where isEqualToString:@"upPush"] == YES || [where isEqualToString:nil] == YES) {
            for (Travel *t in temp) {
                [self.arr addObject:t];
            }
            [self.tableView reloadData];
            // 拿到当前的上拉刷新控件，结束刷新状态
            [self.tableView.footer endRefreshing];
        } else if ([where isEqualToString:@"downPush"] == YES) {
            self.arr = [NSMutableArray array];
            for (NSInteger i = temp.count - 1; i >= 0 ; i--) {
                Travel *t = temp[i];
                [self.arr insertObject:t atIndex:0];
            }
            [self.tableView reloadData];
            // 拿到当前的下拉刷新控件，结束刷新状态
            [self.tableView.header endRefreshing];
        }
        self.collectionView.hidden = YES;
    }];
}
- (void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.contentInset = UIEdgeInsetsMake(10, 0, 70, 0);
    [self.view addSubview:self.tableView];
    [_tableView release];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TravelTableViewCell *cell = [TravelTableViewCell tableView:tableView indexPath:indexPath];
    [cell.backImg setImage:[UIImage imageNamed:@"Navbar_mask"]];
    cell.travel = self.arr[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return (self.view.frame.size.height - 49 - 64 - 40 - 10) / 2;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TravelPushViewController *travelPvc = [[TravelPushViewController alloc] init];
//    travelPvc.url = [NSString stringWithFormat:@"http://chanyouji.com/api/trips/%@.json", [self.arr[indexPath.row] TravelId]];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    travelPvc.number = [self.arr[indexPath.row] TravelId].integerValue;
    [self.navigationController pushViewController:travelPvc animated:YES];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSArray *visibleCells = [self.tableView visibleCells];
    for (TravelTableViewCell *cell in visibleCells) {
        [cell cellOnTableView:self.tableView didScrollOnView:self.view];
    }
}
#pragma mark - 开始拖拽
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    self.tabBarController.tabBar.hidden = YES;
}
#pragma mark - 结束减速
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    self.tabBarController.tabBar.hidden = NO;
}
- (void)setSearchResultVc
{
    self.searchRvc = [[SearchResultViewController alloc] init];
    self.searchRvc.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 30);
    [self addChildViewController:self.searchRvc];
    [self.view addSubview:self.searchRvc.view];
    [self.searchRvc didMoveToParentViewController:self];
    self.searchRvc.view.hidden = YES;
    [_searchRvc release];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
